import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class threadTest {
    public static void main(String[] args) {
        System.out.println(method(3, 2));
    }

    /**
     * @param threadNum 线程池的数量
     * @param timeOut   超时时限
     * @return 返回执行结果
     */
    public static String method(int threadNum, int timeOut) {

        // 获取线程池
        ExecutorService es = Executors.newFixedThreadPool(threadNum);

        // Future用于执行多线程的执行结果
        Future<String> future = es.submit(() -> {
            String s = "程序执行代码";
            return s;
        });

        try {
            // futrue.get()测试被执行的程序是否能在timeOut时限内返回字符串
            return future.get(timeOut, TimeUnit.SECONDS);//任务处理超时时间设为 1 秒
        } catch (Exception ex) {
            System.out.println("输出异常：" + ex.getMessage());
        } finally {
            // 关闭线程池
            es.shutdown();
        }
        return null;
    }
}


